package com.whirl.org.controller;

import com.whirl.basic.utils.AjaxResult;
import com.whirl.basic.utils.PageList;
import com.whirl.org.entity.Department;
import com.whirl.org.query.DepartmentQuery;
import com.whirl.org.service.DepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaowei
 * @date 2022/6/13 12:24
 */

@RestController
@RequestMapping("/dept")
@Api(tags = "部门接口",description = "部门接口详细描述")
public class DepartmentController {
    @Autowired
    DepartmentService departmentService;

    // 根据id删除部门
    @DeleteMapping("/{id}")
    public AjaxResult deleteById(@PathVariable Long id) {
        try {
            departmentService.deleteById(id);
            return AjaxResult.createSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.createError();
        }
    }

    // 批量删除部门
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody List<Long> ids) {
        try {
            departmentService.patchDelete(ids);
            return AjaxResult.createSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.createError();
        }
    }


    // 根据id查询部门
    @GetMapping("/{id}")
    public Department selectById(@PathVariable Long id) {
        return departmentService.selectById(id);
    }

    // 查询所有部门
    @GetMapping
    public List<Department> selectAll() {
        return departmentService.selectAll();
    }
    // 查询所有下级部门
    @GetMapping("/tree")
    public List<Department> queryTree() {
        return departmentService.queryTree();
    }

    /**
     * 新增或者更新部门  根据id判断
     * RequestBody 可以接收json格式的数据
     *
     * @param department
     */
    @PutMapping
    @ApiOperation(value = "部门添加或修改",notes = "如果有id就是修改否则就是添加")
    public AjaxResult addOrUpdate(@RequestBody Department department) {
        try {
            if (department.getId() == null) {
                System.out.println("新增部门");
                departmentService.insert(department);
            } else {
                System.out.println("更新部门");
                departmentService.update(department);
            }
            return AjaxResult.createSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.createError();
        }
    }

    // 查询部门分页
    @PostMapping
    public PageList<Department> queryPage(@RequestBody DepartmentQuery query) {
        return departmentService.queryPage(query);
    }
}
